﻿using Elmah;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Configuration;
using System.Net.Mail;
using System.Web;
using System.Web.Configuration;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using nplJobsCommon.Employeer;
using nplJobsBLL.ProcessEmployeer;
using System.IO;
using nplJobsBLL.ProcessSelectJobSeeker;
using nplJobsCommon.JobSeeker;
using System.Text;

public partial class Employeer_ChangePassword : BasePage // System.Web.UI.Page
{
    #region Page Events
    protected void Page_PreRender(object sender, EventArgs e)
    {
        TextBox CurrentPassword = (TextBox)ChangePwd.ChangePasswordTemplateContainer.FindControl("CurrentPassword");
        CurrentPassword.Text = string.Empty;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Context.User.Identity.IsAuthenticated)
            Response.Redirect("~/Default.aspx", false);

        if (!IsPostBack)
        {
            Label lblTitle = Page.Master.FindControl("lblTitle") != null ? (Label)Page.Master.FindControl("lblTitle") : new Label();
            lblTitle.Text = "Change password";

            TextBox CurrentPassword = (TextBox)ChangePwd.ChangePasswordTemplateContainer.FindControl("CurrentPassword");
            CurrentPassword.Text = string.Empty;

            //ValidationSummary valSumChangePass = (ValidationSummary)ChangePwd.ChangePasswordTemplateContainer.FindControl("valSumChangePass");
            //valSumChangePass.ValidationGroup = "changePass";

            Page.Title = "Change password";
        }

    }
    protected void cusCurrentPass_ServerValidate(object sender, ServerValidateEventArgs e)
    {
        TextBox CurrentPassword = (TextBox)ChangePwd.ChangePasswordTemplateContainer.FindControl("CurrentPassword");

        if (Membership.ValidateUser(User.Identity.Name, CurrentPassword.Text))
        {
            e.IsValid = true;
        }
        else
        {
            e.IsValid = false;
        }
    }
    protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
    {
        if (e.Value.Length >= 6)
        {
            e.IsValid = true;
        }
        else
        {
            e.IsValid = false;
        }
    }
    //protected void ChangePwd_SendingMail(object sender, MailMessageEventArgs e)
    //{
    //    //send email to user with their password
    //    String currentTime = DateTime.Now.ToString("MM-dd-yyyy hh:mm tt");
    //    String username = ChangePwd.UserName;
    //    MailMessage email = e.Message;
    //    email.Subject = " Password Information";
    //    Configuration webConfig = WebConfigurationManager.OpenWebConfiguration("~");
    //    MailSettingsSectionGroup mailSettings = (MailSettingsSectionGroup)webConfig.GetSectionGroup("system.net/mailSettings");
    //    NetworkCredential MailAuthentication = new NetworkCredential(mailSettings.Smtp.From, mailSettings.Smtp.Network.Password);
    //    SmtpClient smtpClient = new SmtpClient(mailSettings.Smtp.Network.Host, mailSettings.Smtp.Network.Port);
    //    smtpClient.EnableSsl = true;
    //    smtpClient.UseDefaultCredentials = false;
    //    smtpClient.Credentials = MailAuthentication;
    //    if (email.From == null || String.IsNullOrEmpty(email.From.Address))
    //    {
    //        email.From = new MailAddress(mailSettings.Smtp.From, " Web Support Administrator");
    //    }
    //    smtpClient.Send(email);
    //    //have to do this otherwise you'll still see the error message from Gmail
    //    e.Cancel = true;
    //}
    protected void ChangePwd_SendMailError(object sender, SendMailErrorEventArgs e)
    {
        string ss = e.Exception.ToString();
        lblSaveMsg.ForeColor = Color.Green;
        lblSaveMsg.Text = "Could not send email to confirm password change.";

        // The MySamplesSite event source has already been created by an administrator.
        System.Diagnostics.EventLog myLog = new System.Diagnostics.EventLog();
        myLog.Log = "Application";
        myLog.Source = "MySamplesSite";
        myLog.WriteEntry("Sending mail via SMTP failed with the following error: " + e.Exception.Message.ToString(), System.Diagnostics.EventLogEntryType.Error);

        e.Handled = true;
    }
    protected void ChangePasswordPushButton_Click(object sender, EventArgs e)
    {
        PasswordChange();
    }
    #endregion

    #region PasswordChange
    private Employeer GetEmployeer(Guid employeerId)
    {
        Employeer employeer = new Employeer();
        ProcessSelectEmployeer selectEmployeer = new ProcessSelectEmployeer();

        selectEmployeer.employeerID = employeerId;
        selectEmployeer.invoke();

        if (selectEmployeer.Employeer != null)
        {
            employeer = selectEmployeer.Employeer.FirstOrDefault();
        }

        return employeer;
    }

    private void PasswordChange()
    {
        try
        {
            Page.Validate("changePass");
            if (!Page.IsValid)
            {
                return;
            }

            MembershipUser u = Membership.GetUser(User.Identity.Name);
            TextBox NewPassword = (TextBox)ChangePwd.ChangePasswordTemplateContainer.FindControl("NewPassword");
            TextBox CurrentPassword = (TextBox)ChangePwd.ChangePasswordTemplateContainer.FindControl("CurrentPassword");
            if (u.ChangePassword(CurrentPassword.Text, NewPassword.Text))
            {
                //Update Employeer table
                Employeer emp = GetEmployeer((Guid)u.ProviderUserKey);
                emp.Password = NewPassword.Text;
                ProcessInserEmployeer employeerinsert = new ProcessInserEmployeer();
                employeerinsert.Employeer = emp;
                employeerinsert.Update();


                GotoSuccessTemplate();
                SendMail();
                bool isValidated = Membership.ValidateUser(User.Identity.Name, CurrentPassword.Text);
                Session["p"] = isValidated;

                lblSaveMsg.ForeColor = Color.Green;
                lblSaveMsg.Text = "Password changed successfully";
                ScriptManager.RegisterStartupScript(this, GetType(), "ClearSaveMsg", "ClearSaveMsg();", true);


            }
            else
            {
                Session["p"] = null;
                ChangePwd.ChangePasswordTemplateContainer.Visible = true;
                Literal lt = this.ChangePwd.ChangePasswordTemplateContainer.FindControl("FailureText") as Literal;
                lt.Text = "Password change failed. Please re-enter your values and try again.";
            }
        }
        catch (Exception ex)
        {
            Literal lt = this.ChangePwd.ChangePasswordTemplateContainer.FindControl("FailureText") as Literal;
            lt.Text = ex.Message;
            ErrorSignal.FromCurrentContext().Raise(ex);
        }
    }
    #endregion

    private static string GetMailBody()
    {
        string domainName = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpContext.Current.Request.ApplicationPath;
        StringBuilder sb = new StringBuilder();
        try
        {
            using (StreamReader _sr = new StreamReader(HttpContext.Current.Server.MapPath("/Resources/ChanedPasswordTemplete.txt")))
            {
                String line = _sr.ReadToEnd();
                sb.Append(line);
            }
        }
        catch (Exception ex)
        {
            ErrorSignal.FromCurrentContext().Raise(ex);

        }
        return sb.ToString();
    }

    #region SendMail
    private void SendMail()
    {
        try
        {
            Configuration webConfig = WebConfigurationManager.OpenWebConfiguration("~");
            MailSettingsSectionGroup mailSettings = (MailSettingsSectionGroup)webConfig.GetSectionGroup("system.net/mailSettings");

            MembershipUser user = Membership.GetUser();
            if (user != null)
            {

                MembershipUser u = Membership.GetUser(User.Identity.Name);
                HttpContext.Current.Session["UserID"] = u != null ? u.ProviderUserKey : null;

                //string Body = "Dear " + user.UserName + "," + "<br/>Your New Password: <br />" + ChangePwd.NewPassword.ToString() + "<br/> and your old Password was :" + "<br/>" + ChangePwd.CurrentPassword;
                string logo_link = "http://www.npljobs.com/Images/npljobs.jpg";
                string Body = GetMailBody().Replace("<%NPL_LOGO%>", logo_link).Replace("<%USER_NAME%>", user.UserName).Replace("<%NEW_PASSWORD%>", ChangePwd.NewPassword.ToString()).Replace("<%OLD_PASSWORD%>", ChangePwd.CurrentPassword).Replace("<%VerificationUrl%>", "http://www.npljobs.com");


            
                string Email = mailSettings.Smtp.From;
                string password = mailSettings.Smtp.Network.Password;
                string emailTo = user.UserName;
                string Subject = "Password changed successfuly";

                using (MailMessage mail = new MailMessage())
                {
                    mail.From = new MailAddress(Email);
                    mail.To.Add(emailTo);
                    mail.Subject = Subject;
                    mail.Body = Body;
                    mail.IsBodyHtml = true;
                    // Can set to false, if you are sending pure text.

                    using (SmtpClient smtpClient = new SmtpClient(mailSettings.Smtp.Network.Host, mailSettings.Smtp.Network.Port))
                    {
                        smtpClient.Credentials = new NetworkCredential(Email, password);
                        smtpClient.EnableSsl = false;
                        smtpClient.Send(mail);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            ErrorSignal.FromCurrentContext().Raise(ex);
        }
    }
    #endregion

    #region GotoSuccessTemplate
    private void GotoSuccessTemplate()
    {
        //ChangePwd.SuccessTemplateContainer.Controls.Clear();
        //ChangePwd.SuccessTemplate.InstantiateIn(ChangePwd);
        //ChangePwd.ChangePasswordTemplateContainer.Visible = false;
    }
    #endregion
}